package com.mingqijia.gassafety.webserver.service.zj.impl;

import static com.mingqijia.gassafety.shared.constant.Constants.BIND_CHANNEL_ZJ_WIFI;
import static com.mingqijia.gassafety.shared.constant.Constants.CONSUMER_TYPE_ZJ;
import static com.mingqijia.gassafety.shared.constant.Constants.ZJ_INDUSTRY_TYPE;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.mingqijia.gassafety.db.entity.*;
import com.mingqijia.gassafety.shared.utils.message.AppletMessageService;
import com.mingqijia.gassafety.webserver.request.inner.*;
import com.mingqijia.gassafety.webserver.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gap.basic.exception.BizException;
import com.mingqijia.gassafety.db.mapper.DepartmentMapper;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.PushMsgEnum;
import com.mingqijia.gassafety.shared.dto.cms.CmsInfoResDTO;
import com.mingqijia.gassafety.shared.utils.message.AppMessageService;
import com.mingqijia.gassafety.shared.utils.message.CmsMessageService;
import com.mingqijia.gassafety.shared.utils.message.SendMessageService;
import com.mingqijia.gassafety.shared.vcc.VccAuthoritiesProvider;
import com.mingqijia.gassafety.webserver.feign.ConsoleSkFeignClient;
import com.mingqijia.gassafety.webserver.request.BindingPositionRequest;
import com.mingqijia.gassafety.webserver.request.ConsumerBindingRequest;
import com.mingqijia.gassafety.webserver.request.ConsumerunBindingRequest;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkUserData;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkUserListResponse;
import com.mingqijia.gassafety.webserver.service.impl.CompanyServiceImpl;
import com.mingqijia.gassafety.webserver.service.workorder.WorkOrderHistoryService;
import com.mingqijia.gassafety.webserver.service.zj.ZjWifiService;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;

/**
 * @program: gassafety
 * @description:
 * @author: guoliang.lao
 * @create: 2023-03-28 14:38
 **/
@Service
@Slf4j
public class ZjWifiServiceImpl implements ZjWifiService {
    @Autowired
    VccAuthoritiesProvider provider;

    @Autowired
    ConsumerService consumerService;

    @Autowired
    EquipmentService equipmentService;

    @Autowired
    DepartmentMapper departmentMapper;

    @Autowired
    WorkOrderHistoryService workOrderHistoryService;

    @Autowired
    ReceiverValveService receiverValveService;

    @Autowired
    BusinessNoticeService businessNoticeService;

    @Autowired
    PushMsgService pushMsgService;

    @Autowired
    AppMessageService appMessageService;

    @Autowired
    SendMessageService sendMessageService;

    @Autowired
    CmsMessageService cmsMessageService;

    @Autowired
    CompanyServiceImpl companyService;

    @Autowired
    FieldTemplateService fieldTemplateService;

    @Autowired
    RecordControllerService recordControllerService;

    @Autowired
    ConsoleSkFeignClient consoleSkFeignClient;
    
    @Autowired
    ConsumerLocationService consumerLocationService;

    @Autowired
    AppletMessageService appletMessageService;

    @Autowired
    RecordDtuService recordDtuService;

    @Autowired
    ContactsService contactsService;

    @Autowired
    DictionaryService dictionaryService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void createConsumerBind(ZJCreateBindRequest request) {
        String spId = request.getSpId();
        // 判断该 用户id是否存在
        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Consumer::getMemberId, request.getMemberId())
                .eq(Consumer::getPhone, request.getPhone()).eq(Consumer::getSpId, spId);
        Consumer consumer = consumerService.getOne(queryWrapper);
        if (consumer != null) {
            // 用户被删除 or 用户已存在
            if (consumer.getIsDeleted()) { // 用户被删除
                // spId，去department表里查
                QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper<>();
                departmentQueryWrapper.lambda().eq(Department::getSpId, spId);
                Department department = departmentMapper.selectOne(departmentQueryWrapper);
                Consumer consumerNew = new Consumer();
                consumerNew.setPositionLat(request.getPositionLat());
                consumerNew.setPositionLon(request.getPositionLon());
                consumerNew.setDepartmentId(department.getId());
                consumerNew.setPath(department.getPath());
                consumerNew.setIndustryType(ZJ_INDUSTRY_TYPE);
                consumerNew.setStatusAnyalert(false);
                consumerNew.setStatusAnybroken(false);
                consumerNew.setStatusAnyoffline(false);
                consumerNew.setStatusAnynormal(true);
                consumerNew.setStatusUpdatetime(new Date());
                consumerNew.setIsDeleted(false);
                consumerNew.setId(consumer.getId());
                consumerNew.setCreatedAt(new Date());
                consumerNew.setCustName("");
                consumerNew.setCustPhone("");
                consumerNew.setCustType("");
                consumerNew.setCustStatus("");
                consumerNew.setCustAddress("");
                consumerNew.setSubsCode("");
                consumerNew.setAddress("");
                consumerService.updateById(consumerNew);

                consumerLocationService.updateConsumerLocation(consumerNew);
            }
        } else {
            // 用户不存在,创建对应客户
            // spId，去department表里查
            QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper<>();
            departmentQueryWrapper.lambda().eq(Department::getSpId, spId);
            Department department = departmentMapper.selectOne(departmentQueryWrapper);
            Consumer consumerAdd = new Consumer();
            consumerAdd.setConsumerType(CONSUMER_TYPE_ZJ);
            consumerAdd.setMemberId(request.getMemberId());
            consumerAdd.setName(request.getName());
            consumerAdd.setPhone(request.getPhone());
            consumerAdd.setPositionLat(request.getPositionLat());
            consumerAdd.setPositionLon(request.getPositionLon());
            consumerAdd.setDepartmentId(department.getId());
            consumerAdd.setPath(department.getPath());
            consumerAdd.setIndustryType(ZJ_INDUSTRY_TYPE);
            consumerAdd.setSpId(spId);
            consumerAdd.setStatusAnyalert(false);
            consumerAdd.setStatusAnybroken(false);
            consumerAdd.setStatusAnyoffline(false);
            consumerAdd.setStatusAnynormal(true);
            consumerAdd.setStatusUpdatetime(new Date());
            consumerService.save(consumerAdd);

            consumerLocationService.updateConsumerLocation(consumerAdd);
        }
        // 添加设备
        int count = equipmentService.saveZJWifiDevice(request);
        if (count > 0) {
            // 添加接收器和电磁阀
            ReceiverValve receiverValve = new ReceiverValve();
            receiverValve.setReceiverCode(request.getReceiverCode());
            receiverValve.setDeviceId(request.getImei());
            receiverValve.setSpId(spId);
            receiverValveService.addReceiverValve(receiverValve);

            // 获取客户id
            queryWrapper.lambda().eq(Consumer::getIsDeleted, false);
            Consumer consumerNow = consumerService.getOne(queryWrapper);
            log.info("客户id:{}", consumerNow.getId());
            // 构建入参
            ConsumerBindingRequest bindingRequest = new ConsumerBindingRequest();
            List<BindingPositionRequest> list = new ArrayList<>();
            BindingPositionRequest bindingPositionRequest = new BindingPositionRequest();
            bindingPositionRequest.setImei(request.getImei());
            bindingPositionRequest.setInstallationPosition("");
            list.add(bindingPositionRequest);

            bindingRequest.setConsumerId(consumerNow.getId());
            bindingRequest.setImeiList(list);
            bindingRequest.setBindChannel(BIND_CHANNEL_ZJ_WIFI);
            bindingRequest.setSpId(spId);
            log.info("客户绑定设备入参, ConsumerBindingRequest :{}", bindingRequest.toString());
            consumerService.bindingEquipment(bindingRequest);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void createConsumerBindZJ(ZJCreateBindRequest request) {
        String spId = dictionaryService.selectZJSpMapping(request.getSpId());
        String dtuRemark = "";
        if (!spId.equals(request.getSpId())) {
            dtuRemark = "来源于映射企业："+request.getSpId();
        }
        request.setDtuRemark(dtuRemark);
        request.setSpId(spId);
        // 根据设备的imei号查询到spid
        QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
        dtuQueryWrapper.lambda().eq(Dtu::getIMEI, request.getImei())
                .eq(Dtu::getIsDeleted, 0);
        Dtu dtu = equipmentService.getOne(dtuQueryWrapper);
        Consumer consumer = null;
        // 判断该 用户id是否存在
        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
        if (dtu != null && dtu.getConsumerId() != null && dtu.getConsumerId() > 0) {
            // 判断该 用户id是否存在
            queryWrapper.lambda().eq(Consumer::getId, dtu.getConsumerId()).eq(Consumer::getSpId, dtu.getSpId())
                    .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE);
            consumer = consumerService.getOne(queryWrapper);
            spId = dtu.getSpId();
        }
        Consumer consumerNow = new Consumer();
        if (consumer != null) {
            // spId，去department表里查
            QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper<>();
            departmentQueryWrapper.lambda().eq(Department::getSpId, spId);
            Department department = departmentMapper.selectOne(departmentQueryWrapper);
            Consumer consumerNew = new Consumer();
            consumerNew.setName(request.getName());
            consumerNew.setPhone(request.getPhone());
            if (consumer.getDataSource() == 1) {
                consumerNew.setPositionLat(Double.valueOf(request.getPositionLat()));
                consumerNew.setPositionLon(Double.valueOf(request.getPositionLon()));
            } else {
                if (consumer.getPositionLat() == null) {
                    consumerNew.setPositionLat(Double.valueOf(request.getPositionLat()));
                    consumerNew.setPositionLon(Double.valueOf(request.getPositionLon()));
                }
            }
            consumerNew.setDepartmentId(department.getId());
            consumerNew.setPath(department.getPath());
            consumerNew.setIndustryType(ZJ_INDUSTRY_TYPE);
            consumerNew.setStatusAnyalert(false);
            consumerNew.setStatusAnybroken(false);
            consumerNew.setStatusAnyoffline(false);
            consumerNew.setStatusAnynormal(true);
            consumerNew.setStatusUpdatetime(new Date());
            consumerNew.setIsDeleted(false);
            consumerNew.setId(consumer.getId());
            consumerNew.setCreatedAt(new Date());
            consumerNew.setCustName("");
            consumerNew.setCustPhone("");
            consumerNew.setCustType("");
            consumerNew.setCustStatus("");
            consumerNew.setCustAddress("");
            consumerNew.setSubsCode("");
            consumerNew.setAddress("");
            consumerService.updateById(consumerNew);
            consumerNow = consumerNew;
        } else {
            // 用户不存在,创建对应客户
            // spId，去department表里查
            QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper<>();
            departmentQueryWrapper.lambda().eq(Department::getSpId, spId);
            Department department = departmentMapper.selectOne(departmentQueryWrapper);
            Consumer consumerAdd = new Consumer();
            consumerAdd.setConsumerType(CONSUMER_TYPE_ZJ);
            consumerAdd.setName(request.getName());
            consumerAdd.setPhone(request.getPhone());
            consumerAdd.setPositionLat(Double.valueOf(request.getPositionLat()));
            consumerAdd.setPositionLon(Double.valueOf(request.getPositionLon()));
            consumerAdd.setDepartmentId(department.getId());
            consumerAdd.setPath(department.getPath());
            consumerAdd.setIndustryType(ZJ_INDUSTRY_TYPE);
            consumerAdd.setSpId(spId);
            consumerAdd.setStatusAnyalert(false);
            consumerAdd.setStatusAnybroken(false);
            consumerAdd.setStatusAnyoffline(false);
            consumerAdd.setStatusAnynormal(true);
            consumerAdd.setStatusUpdatetime(new Date());
            consumerAdd.setDataSource(1);
            consumerService.save(consumerAdd);
            consumerNow = consumerAdd;
        }
        // 更新t_consumer_location表数据
        consumerLocationService.updateConsumerLocation(consumerNow);
        contactsService.addUpdateContacts(consumerNow);

        // 添加设备
        int count = equipmentService.saveUpdateZJWifiDevice(request);
        if (count > 0) {
            log.info("客户id:{}", consumerNow.getId());
            // 构建入参
            ConsumerBindingRequest bindingRequest = new ConsumerBindingRequest();
            List<BindingPositionRequest> list = new ArrayList<>();
            BindingPositionRequest bindingPositionRequest = new BindingPositionRequest();
            bindingPositionRequest.setImei(request.getImei());
            bindingPositionRequest.setInstallationPosition("");
            list.add(bindingPositionRequest);

            bindingRequest.setConsumerId(consumerNow.getId());
            bindingRequest.setImeiList(list);
            bindingRequest.setBindChannel(BIND_CHANNEL_ZJ_WIFI);
            bindingRequest.setSpId(spId);
            log.info("客户绑定设备入参, ConsumerBindingRequest :{}", bindingRequest.toString());
            consumerService.bindingEquipmentZJ(bindingRequest);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void unbindEquipment(ZJUnBindRequest request) {
        String spId = "";
        ConsumerunBindingRequest bindingRequest = new ConsumerunBindingRequest();
        bindingRequest.setImei(request.getImei());
        // 根据设备的imei号查询到spid
        QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
        dtuQueryWrapper.lambda().eq(Dtu::getIMEI, request.getImei()).eq(Dtu::getIsDeleted, 0);
        Dtu dtu = equipmentService.getOne(dtuQueryWrapper);
        // 根据 用户id查询对应客户id
        QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
        consumerQueryWrapper.lambda().eq(Consumer::getId, dtu.getConsumerId())
                .eq(Consumer::getPhone, request.getPhone()).eq(Consumer::getIsDeleted, false)
                .eq(Consumer::getSpId, dtu.getSpId());
        List<Consumer> consumers = consumerService.list(consumerQueryWrapper);
        if (dtu != null && CollectionUtil.isNotEmpty(consumers)) {
            spId = dtu.getSpId();
            bindingRequest.setConsumerId(consumers.get(0).getId());
        } else {
            throw new BizException("用户id:" + request.getMemberId() + ",未创建客户");
        }
        bindingRequest.setTemplateType(fieldTemplateService.getBySpId(spId));
        // 渠道一和渠道二走同一个解绑逻辑
        bindingRequest.setSpId(spId);
        bindingRequest.setBindChannel(BIND_CHANNEL_ZJ_WIFI);
        consumerService.unbindEquipment(bindingRequest);
    }

    /**
     * APP消息推送&短信发送
     *
     * @param dtu  设备
     * @param type 1:报警器泄漏 2:报警器故障 3:报警器寿命到期 4:接收器电池欠压（低于2.7V时） 5:接收器电池欠压（低于2.4V时）6:报警器离线 7:接收器离线 8:电磁阀关闭 * 9:接收器状态阀故障
     *             10:接收器状态阀断开
     */
    @Override
    public void pushMsg(Dtu dtu, Integer type) {
        // 紫荆WiFi报警器G
        log.info("APP消息推送&短信发送 start{}", dtu.getId());
        log.info("APP消息推送&短信发送，imei：{}，equipmentFrom：{}，type:{}", dtu.getIMEI(), dtu.getEquipmentFrom(), type);
        List<Integer> types = Arrays.asList(1,2,3,11,12);
        if (Constants.ZJ_EQUIPMENT_FROM.equals(dtu.getEquipmentFrom()) || types.contains(type)) {

            String spId = dtu.getSpId();
            // 查询并拼接消息体
            QueryWrapper<BusinessNotice> query1 = new QueryWrapper<>();
            query1.lambda().or().eq(BusinessNotice::getIsDeleted, 0).eq(BusinessNotice::getSpId, spId)
                    .eq(BusinessNotice::getParamCode, "cm_service_hot_line");
            String orgCode = companyService.getOrgCode(spId, dtu.getConsumerId() + "");
            log.info("APP消息推送&短信发送，orgCode:{}",orgCode);
            String phone = provider.getOrgInfoTel(orgCode);
            log.info("APP消息推送&短信发送，phone:{}",phone);
            String msg = null;
            if (type != 1 && type != 2 && type != 3 && type != 11 && type != 12) {
                 msg = String.format(PushMsgEnum.getText(type), phone);
                if (StringUtils.isEmpty(msg))
                    log.info("消息为空不发送");
            }
            String title = PushMsgEnum.getTitle(type);
            Consumer consumer = consumerService.getById(dtu.getConsumerId());
            if (consumer == null)
                log.info(dtu.getConsumerId() + "客户不存在，不发送");
//            if (StringUtils.isEmpty(consumer.getMemberId())){
//                log.info(consumer.getMemberId() + "用户id不存在，不发送");
//            }
            if (StringUtils.isEmpty(consumer.getPhone()))
                log.info(consumer.getPhone() + "用户手机号不存在，不发送");
            boolean pushResult = false;

            Map map = new HashMap();
            if (Constants.ZJ_EQUIPMENT_FROM.equals(dtu.getEquipmentFrom())) {
                log.info("APP消息推送&短信发送 紫荆设备短信推送");
                Map<String, Object> param = new HashMap<>();
                param.put("phone", phone);
                Map<String, Object> jsonData = sendMessageService.getRequestParam(consumer.getPhone(),
                        PushMsgEnum.getCode(type), orgCode, param, "sms", null, null, null, Constants.ZJ_EQUIPMENT_FROM);
                map = sendMessageService.sendSms(jsonData, spId);
            }

            // 处理站内信逻辑：update by wangwei
            // 需要给家庭成员发送三条站内信


            log.info("查询家庭成员" + dtu.getIMEI());
            ConsoleSkUserListResponse consoleSkUserListResponse;
            if (dtu.getIMEI().contains("-")) {
                String[] imeis = StringUtils.split(dtu.getIMEI(), "-");
                consoleSkUserListResponse = consoleSkFeignClient
                        .alarmSOSUserList(imeis[0]);
            }
            else {
                consoleSkUserListResponse = consoleSkFeignClient
                        .alarmSOSUserList(dtu.getIMEI());
            }

            log.info(new StringBuilder().append("需要给").append(dtu.getIMEI()).append("的家庭成员发送信息，信息如下")
                    .append(consoleSkUserListResponse).toString());
            if (consoleSkUserListResponse != null && consoleSkUserListResponse.getData() != null
                    && CollectionUtil.isNotEmpty(consoleSkUserListResponse.getData().getUserList())) {
                log.info("msg的值为" + msg);
                if (!StringUtils.isEmpty(msg)) {
                    // 循环发送家庭其他成员
                    for (ConsoleSkUserData consoleSkUserData : consoleSkUserListResponse.getData().getUserList()) {
                        if (consoleSkUserData.getUserRole() == 0) {
                            if (org.apache.commons.lang3.StringUtils.isNotEmpty(msg) ) {
                                pushResult = appMessageService.sendSms(appMessageService.getRequestParam(new String[]{
                                        String.valueOf(consoleSkUserData.getUserId())
                                }, msg, PushMsgEnum.getTitle(type)));
                            }
                            // 站内信参数封装
                            JSONObject cmsReqParams = cmsMessageService.getCmsJSONParams(msg, title,
                                    consoleSkUserData.getUserId());
                            // 站内信发送
                            CmsInfoResDTO cmsInfoResDTO = cmsMessageService.sendCmsMsg(cmsReqParams);

                            // 定时器会自动发剩下来的几条短信
                            PushMsg pushMsg = new PushMsg();
                            pushMsg.setDeviceId(dtu.getIMEI());
                            pushMsg.setMemberId(consumer.getMemberId());
                            pushMsg.setPhone(consumer.getPhone());
                            pushMsg.setPushType(type);
                            pushMsg.setPushText(msg);

                            if (!Constants.ZJ_EQUIPMENT_FROM.equals(dtu.getEquipmentFrom())) {
                                pushMsg.setPushTimes(-1);
                            } else if (!pushResult) {
                                pushMsg.setPushTimes(0);
                            }

                            if (!Constants.ZJ_EQUIPMENT_FROM.equals(dtu.getEquipmentFrom())) {
                                pushMsg.setSendTimes(-1);//短信不推送
                            } else if (map.get("result") != null && !Boolean.valueOf(map.get("result").toString())) {
                                pushMsg.setSendTimes(0);
                            }

                            if (!Constants.ZJ_EQUIPMENT_FROM.equals(dtu.getEquipmentFrom())) {
                                pushMsg.setSendCmsTimes(-1);
                            }else if (ObjectUtil.isEmpty(cmsInfoResDTO) || cmsInfoResDTO.getCode() != 0) {
                                pushMsg.setSendCmsTimes(0);
                            }
                            pushMsg.setMsgCode(PushMsgEnum.getCode(type));
                            pushMsg.setSpId(spId);
                            pushMsgService.save(pushMsg);
                            log.info("新增时刻家APP消息推送和短信发送记录表：" + pushMsg.toString());
                        }
                        else {
                            // 站内信参数封装
                            JSONObject cmsReqParams = cmsMessageService.getCmsJSONParams(msg, title,
                                    consoleSkUserData.getUserId());
                            // 站内信发送
                            CmsInfoResDTO cmsInfoResDTO = cmsMessageService.sendCmsMsg(cmsReqParams);

                            // 定时器会自动发剩下来的几条短信
                            PushMsg pushMsg = new PushMsg();
                            pushMsg.setDeviceId(dtu.getIMEI());
                            pushMsg.setMemberId(consoleSkUserData.getUserId().toString());
                            pushMsg.setPhone(consumer.getPhone());
                            pushMsg.setPushType(type);
                            pushMsg.setPushText(msg);
                            pushMsg.setPushTimes(-1); // APP不推送
                            pushMsg.setSendTimes(-1); // 短信不推送

                            if (!Constants.ZJ_EQUIPMENT_FROM.equals(dtu.getEquipmentFrom())) {
                                pushMsg.setSendCmsTimes(-1);
                            } else if (ObjectUtil.isEmpty(cmsInfoResDTO) || cmsInfoResDTO.getCode() != 0) {
                                // 站内信如果发送失败，从0开始发，定时任务会发3次
                                pushMsg.setSendCmsTimes(0);
                            }
                            pushMsg.setMsgCode(PushMsgEnum.getCode(type));
                            pushMsg.setSpId(spId);
                            pushMsgService.save(pushMsg);
                        }
                    }
                } else {
                    String msgs = null;
                    log.info("type的值为" + type);
                    if (type == 12) {
                        if (StringUtils.isEmpty(consoleSkUserListResponse.getData().getRoomName())) {
                            msgs = String.format(PushMsgEnum.getText(type), dtu.getValidity(), consoleSkUserListResponse.getData().getHomeName(), consoleSkUserListResponse.getData().getEquName());
                        } else {
                            msgs = String.format(PushMsgEnum.getText(type), dtu.getValidity(), consoleSkUserListResponse.getData().getHomeName() + " - " + consoleSkUserListResponse.getData().getRoomName(), consoleSkUserListResponse.getData().getEquName());
                        }
                    } else {
                        if (StringUtils.isEmpty(consoleSkUserListResponse.getData().getRoomName())) {
                            msgs = String.format(PushMsgEnum.getText(type), consoleSkUserListResponse.getData().getHomeName(), consoleSkUserListResponse.getData().getEquName());
                        } else {
                            msgs = String.format(PushMsgEnum.getText(type), consoleSkUserListResponse.getData().getHomeName() + " - " + consoleSkUserListResponse.getData().getRoomName(), consoleSkUserListResponse.getData().getEquName());
                        }
                    }
//                    pushResult = appMessageService.sendSms(appMessageService.getRequestParam(new String[]{
//                            consumer.getMemberId()
//                    }, msgs, PushMsgEnum.getTitle(type)));
                    List<RecordDtu> recordDtus;
                    if (dtu.getId().contains("-")) {
                        String[] dtuids = StringUtils.split(dtu.getId(), "-");
                        QueryWrapper<RecordDtu> queryWrapper = new QueryWrapper<>();
                        queryWrapper.lambda().eq(RecordDtu::getDeviceId, dtuids[0])
                                .eq(RecordDtu::getIsDeleted, 0).eq(RecordDtu::getSpId, spId)
                                .orderByDesc(RecordDtu::getRecordAt);
                        recordDtus = recordDtuService.list(queryWrapper);
                    }else {
                        QueryWrapper<RecordDtu> queryWrapper = new QueryWrapper<>();
                        queryWrapper.lambda().eq(RecordDtu::getDeviceId, dtu.getId())
                                .eq(RecordDtu::getIsDeleted, 0).eq(RecordDtu::getSpId, spId)
                                .orderByDesc(RecordDtu::getRecordAt);
                        recordDtus = recordDtuService.list(queryWrapper);
                    }
                    Date date;
                    if (CollectionUtils.isNotEmpty(recordDtus)) {
                        date = recordDtus.get(0).getRecordAt();
                    } else {
                        date = new Date();
                    }
                    // 循环发送家庭其他成员
                    for (ConsoleSkUserData consoleSkUserData : consoleSkUserListResponse.getData().getUserList()) {
                        if (consoleSkUserData.getUserRole() == 0) {
                            if (org.apache.commons.lang3.StringUtils.isNotEmpty(msgs) ) {
                                pushResult = appMessageService.sendSms(appMessageService.getRequestParam(new String[]{
                                        String.valueOf(consoleSkUserData.getUserId())
                                }, msgs, PushMsgEnum.getTitle(type)));
                            }
                            // 站内信参数封装
                            JSONObject cmsReqParams = cmsMessageService.getCmsJSONParams(msgs, title,
                                    consoleSkUserData.getUserId());
                            // 站内信发送
                            CmsInfoResDTO cmsInfoResDTO = cmsMessageService.sendCmsMsg(cmsReqParams);
                            String page;
                            if (dtu.getIMEI().contains("-") || dtu.getDeviceCode().contains("-")) {
                                String[] imeis = StringUtils.split(dtu.getIMEI(), "-");
                                String[] deviceCodes = StringUtils.split(dtu.getDeviceCode(), "-");
                                page = String.format(Constants.WARNINGDEVICE_DETAIL, imeis[0], consoleSkUserListResponse.getData().getHomeId(), imeis[0], deviceCodes[0], consoleSkUserListResponse.getData().getEquName(),
                                        StringUtils.isEmpty(consoleSkUserListResponse.getData().getRoomName()) ? "" : consoleSkUserListResponse.getData().getRoomName());
                            } else {
                                page = String.format(Constants.WARNINGDEVICE_DETAIL, dtu.getIMEI(), consoleSkUserListResponse.getData().getHomeId(), dtu.getIMEI(), dtu.getDeviceCode(), consoleSkUserListResponse.getData().getEquName(),
                                        StringUtils.isEmpty(consoleSkUserListResponse.getData().getRoomName()) ? "" : consoleSkUserListResponse.getData().getRoomName());
                            }
                            // 小程序参数封装
                            JSONObject appletJSONParams = appletMessageService.getAppletJSONParams(consoleSkUserListResponse.getData().getHomeName(), consoleSkUserListResponse.getData().getRoomName(),
                                    consoleSkUserListResponse.getData().getEquName(), consoleSkUserData.getUserId(), title, page, date);
                            // 小程序发送
                            appletMessageService.sendAppletMsg(appletJSONParams);

                            // 定时器会自动发剩下来的几条短信
                            PushMsg pushMsg = new PushMsg();
                            pushMsg.setDeviceId(dtu.getIMEI());
                            pushMsg.setMemberId(consumer.getMemberId());
                            pushMsg.setPhone(consumer.getPhone());
                            pushMsg.setPushType(type);
                            pushMsg.setPushText(msgs);

                            if (!Constants.ZJ_EQUIPMENT_FROM.equals(dtu.getEquipmentFrom())) {
                                pushMsg.setPushTimes(-1);
                            } else if (!pushResult) {
                                pushMsg.setPushTimes(0);
                            }

                            if (!Constants.ZJ_EQUIPMENT_FROM.equals(dtu.getEquipmentFrom())) {
                                pushMsg.setSendTimes(-1);//短信不推送
                            } else if (map.get("result") != null && !Boolean.valueOf(map.get("result").toString())) {
                                pushMsg.setSendTimes(0);
                            }

                            if (!Constants.ZJ_EQUIPMENT_FROM.equals(dtu.getEquipmentFrom())) {
                                pushMsg.setSendCmsTimes(-1);
                            }else if (ObjectUtil.isEmpty(cmsInfoResDTO) || cmsInfoResDTO.getCode() != 0) {
                                pushMsg.setSendCmsTimes(0);
                            }
                            pushMsg.setMsgCode(PushMsgEnum.getCode(type));
                            pushMsg.setSpId(spId);
                            pushMsgService.save(pushMsg);
                            log.info("新增时刻家APP消息推送和短信发送记录表：" + pushMsg.toString());
                        } else {
                            // 站内信参数封装
                            JSONObject cmsReqParams = cmsMessageService.getCmsJSONParams(msgs, title,
                                    consoleSkUserData.getUserId());
                            // 站内信发送
                            CmsInfoResDTO cmsInfoResDTO = cmsMessageService.sendCmsMsg(cmsReqParams);
                            String page;
                            if (dtu.getIMEI().contains("-") || dtu.getDeviceCode().contains("-")) {
                                String[] imeis = StringUtils.split(dtu.getIMEI(), "-");
                                String[] deviceCodes = StringUtils.split(dtu.getDeviceCode(), "-");
                                page = String.format(Constants.WARNINGDEVICE_DETAIL, imeis[0], consoleSkUserListResponse.getData().getHomeId(), imeis[0], deviceCodes[0], consoleSkUserListResponse.getData().getEquName(),
                                        StringUtils.isEmpty(consoleSkUserListResponse.getData().getRoomName()) ? "" : consoleSkUserListResponse.getData().getRoomName());
                            } else {
                                page = String.format(Constants.WARNINGDEVICE_DETAIL, dtu.getIMEI(), consoleSkUserListResponse.getData().getHomeId(), dtu.getIMEI(), dtu.getDeviceCode(), consoleSkUserListResponse.getData().getEquName(),
                                        StringUtils.isEmpty(consoleSkUserListResponse.getData().getRoomName()) ? "" : consoleSkUserListResponse.getData().getRoomName());
                            }
                            // 小程序参数封装
                            JSONObject appletJSONParams = appletMessageService.getAppletJSONParams(consoleSkUserListResponse.getData().getHomeName(), consoleSkUserListResponse.getData().getRoomName(),
                                    consoleSkUserListResponse.getData().getEquName(), consoleSkUserData.getUserId(), title, page, date);
                            // 小程序发送
                            appletMessageService.sendAppletMsg(appletJSONParams);

                            // 定时器会自动发剩下来的几条短信
                            PushMsg pushMsg = new PushMsg();
                            pushMsg.setDeviceId(dtu.getIMEI());
                            pushMsg.setMemberId(consoleSkUserData.getUserId().toString());
                            pushMsg.setPhone(consumer.getPhone());
                            pushMsg.setPushType(type);
                            pushMsg.setPushText(msgs);
                            pushMsg.setPushTimes(0);
                            pushMsg.setSendTimes(-1); // 短信不推送

                            if (!Constants.ZJ_EQUIPMENT_FROM.equals(dtu.getEquipmentFrom())) {
                                pushMsg.setSendCmsTimes(-1);
                            } else if (ObjectUtil.isEmpty(cmsInfoResDTO) || cmsInfoResDTO.getCode() != 0) {
                                // 站内信如果发送失败，从0开始发，定时任务会发3次
                                pushMsg.setSendCmsTimes(0);
                            }
                            pushMsg.setMsgCode(PushMsgEnum.getCode(type));
                            pushMsg.setSpId(spId);
                            pushMsgService.save(pushMsg);
                            log.info("新增时刻家APP小程序消息推送和短信发送记录表：" + pushMsg.toString());
                        }
                    }
                }

            }
            log.info("msg没进去的值为" + msg);
        }
    }

    @Override
    public Integer dataCount(ZJDataCountRequest params) {
        String spId = dictionaryService.selectZJSpMapping(params.getSpId());
        LambdaQueryWrapper<RecordController> query = new LambdaQueryWrapper<>();
        query.eq(RecordController::getSpId, spId).eq(RecordController::getDeviceId, params.getImei())
                .ge(RecordController::getRecordAt, params.getDate());
        return recordControllerService.count(query);
    }

    @Override
    public void deviceRregister(ZJDeviceRegisterRequest request) {
        // 添加设备
        equipmentService.saveZJWifiDevice(request);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deviceBind(ZJDeviceBindRequest request) {
        String spId = dictionaryService.selectZJSpMapping(request.getSpId());

        // 根据设备的imei号查询到spid
        QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
        dtuQueryWrapper.lambda().eq(Dtu::getIMEI, request.getImei())
                .eq(Dtu::getIsDeleted, 0);
        Dtu dtu = equipmentService.getOne(dtuQueryWrapper);
        Consumer consumer = null;
        // 判断该 用户id是否存在
        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
        if (dtu != null && dtu.getConsumerId() != null && dtu.getConsumerId() > 0) {
            // 判断该 用户id是否存在
            queryWrapper.lambda().eq(Consumer::getId, dtu.getConsumerId()).eq(Consumer::getSpId, dtu.getSpId())
                    .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE);
            consumer = consumerService.getOne(queryWrapper);
            spId = dtu.getSpId();
        }
        //log.info("客户具体信息:{}", consumer);
        Consumer consumerNow = new Consumer();
        if (consumer != null) {
            // spId，去department表里查
            QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper<>();
            if (dtu != null) {
                departmentQueryWrapper.lambda().eq(Department::getSpId, dtu.getSpId());
            } else {
                departmentQueryWrapper.lambda().eq(Department::getSpId, spId);
            }
            Department department = departmentMapper.selectOne(departmentQueryWrapper);
            Consumer consumerNew = new Consumer();
            BeanUtils.copyProperties(consumer, consumerNew);
            if (consumer.getDataSource() == 1) {
                consumerNew.setPositionLat(Double.valueOf(request.getPositionLat()));
                consumerNew.setPositionLon(Double.valueOf(request.getPositionLon()));
                consumerNew.setName(request.getName());
                consumerNew.setPhone(request.getPhone());
            } else {
                if (consumer.getPositionLat() == null) {
                    consumerNew.setPositionLat(Double.valueOf(request.getPositionLat()));
                    consumerNew.setPositionLon(Double.valueOf(request.getPositionLon()));
                }
            }
            consumerNew.setDepartmentId(department.getId());
            consumerNew.setPath(department.getPath());
            if (StringUtils.isEmpty(consumer.getIndustryType())) {
                consumerNew.setIndustryType(ZJ_INDUSTRY_TYPE);
            }
            consumerNew.setStatusAnyalert(false);
            consumerNew.setStatusAnybroken(false);
            consumerNew.setStatusAnyoffline(false);
            consumerNew.setStatusAnynormal(true);
            consumerNew.setStatusUpdatetime(new Date());
            consumerNew.setIsDeleted(false);
            consumerNew.setId(consumer.getId());
            consumerService.updateById(consumerNew);
            consumerNow = consumerNew;
            consumerNow.setName(request.getName());
            consumerNow.setPhone(request.getPhone());
        } else {
            // 用户不存在,创建对应客户
            // spId，去department表里查
            QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper<>();
            if (dtu != null) {
                departmentQueryWrapper.lambda().eq(Department::getSpId, dtu.getSpId());
            } else {
                departmentQueryWrapper.lambda().eq(Department::getSpId, spId);
            }

            Department department = departmentMapper.selectOne(departmentQueryWrapper);
            Consumer consumerAdd = new Consumer();
            consumerAdd.setConsumerType(0);
            consumerAdd.setName(request.getName());
            consumerAdd.setPhone(request.getPhone());
            consumerAdd.setPositionLat(Double.valueOf(request.getPositionLat()));
            consumerAdd.setPositionLon(Double.valueOf(request.getPositionLon()));
            consumerAdd.setDepartmentId(department.getId());
            consumerAdd.setPath(department.getPath());
            consumerAdd.setIndustryType(ZJ_INDUSTRY_TYPE);
            if (dtu != null) {
                consumerAdd.setSpId(dtu.getSpId());
            } else {
                consumerAdd.setSpId(spId);
            }
            consumerAdd.setStatusAnyalert(false);
            consumerAdd.setStatusAnybroken(false);
            consumerAdd.setStatusAnyoffline(false);
            consumerAdd.setStatusAnynormal(true);
            consumerAdd.setStatusUpdatetime(new Date());
            consumerAdd.setDataSource(1);
            consumerService.save(consumerAdd);
            consumerNow = consumerAdd;
        }
        // 获取客户id
        log.info("客户id:{}", consumerNow);
        
        // 更新t_consumer_location表数据
        consumerLocationService.updateConsumerLocation(consumerNow);
        contactsService.addUpdateContacts(consumerNow);

        // 构建入参
        ConsumerBindingRequest bindingRequest = new ConsumerBindingRequest();
        List<BindingPositionRequest> list = new ArrayList<>();
        BindingPositionRequest bindingPositionRequest = new BindingPositionRequest();
        bindingPositionRequest.setImei(request.getImei());
        bindingPositionRequest.setInstallationPosition("");
        list.add(bindingPositionRequest);

        bindingRequest.setConsumerId(consumerNow.getId());
        bindingRequest.setImeiList(list);
        bindingRequest.setBindChannel(BIND_CHANNEL_ZJ_WIFI);
        if (dtu != null) {
            bindingRequest.setSpId(dtu.getSpId());
        } else {
            bindingRequest.setSpId(spId);
        }
        log.info("客户绑定设备入参, ConsumerBindingRequest :{}", bindingRequest.toString());
        consumerService.bindingEquipmentZJ(bindingRequest);
    }

    @Override
    public void deviceUnbind(ZJDeviceBindRequest request) {
        String spId = "";
        ConsumerunBindingRequest bindingRequest = new ConsumerunBindingRequest();
        bindingRequest.setImei(request.getImei());
        // 根据设备的imei号查询到spid
        QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
        dtuQueryWrapper.lambda().eq(Dtu::getIMEI, request.getImei()).eq(Dtu::getIsDeleted, 0);
        Dtu dtu = equipmentService.getOne(dtuQueryWrapper);
        // 根据 用户id查询对应客户id
        QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
        consumerQueryWrapper.lambda().eq(Consumer::getId, dtu.getConsumerId())
                .eq(Consumer::getPhone, request.getPhone()).eq(Consumer::getIsDeleted, false)
                .eq(Consumer::getSpId, dtu.getSpId());
        List<Consumer> consumers = consumerService.list(consumerQueryWrapper);
        if (dtu != null && CollectionUtil.isNotEmpty(consumers)) {
            spId = dtu.getSpId();
            bindingRequest.setConsumerId(consumers.get(0).getId());
        } else {
            throw new BizException("用户id:" + request.getMemberId() + ",未创建客户");
        }

        bindingRequest.setTemplateType(fieldTemplateService.getBySpId(spId));
        bindingRequest.setMemberId(request.getMemberId());
        // 渠道一和渠道二走同一个解绑逻辑
        bindingRequest.setSpId(spId);
        bindingRequest.setBindChannel(BIND_CHANNEL_ZJ_WIFI);
        consumerService.unbindMember(bindingRequest);
    }

    @Override
    public void deviceRemove(ZJDeviceRegisterRequest request) {
        equipmentService.equipmentDelete(request.getDeviceCode(), request.getSpId());
    }
}
